package top.lucky.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import top.lucky.entity.User;


import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生成需要盖章pdf工具类
 */
public class SignPdfUtil {

    /**
     * @param templatePath     pdf模板地址
     * @param newPdfParentPath 生成pdf文件路径
     * @param userList
     */
    public static int fillTemplate(String templatePath, String newPdfParentPath, List<User> userList) {

        int i = 0;
        for (int j = 0; j < userList.size(); j++) {
            User user = userList.get(j);
            // 生成的新文件路径
            String newPDFPath = null;
            if (j < 9)
                newPDFPath = newPdfParentPath + user.getName() + "0" + (j + 1) + "_" + "0" + (j + 1) + ".pdf";
             else
                newPDFPath = newPdfParentPath + user.getName() + (j + 1) + "_" + (j + 1) + ".pdf";
            PdfReader reader;
            FileOutputStream out;
            ByteArrayOutputStream bos;
            PdfStamper stamper;
            try {
                out = new FileOutputStream(newPDFPath);
                reader = new PdfReader(templatePath);
                bos = new ByteArrayOutputStream();
                stamper = new PdfStamper(reader, bos);
                AcroFields form = stamper.getAcroFields();
                Map<String, String> map = new HashMap<>();
                map.put("name", user.getName());
                map.put("idCard", user.getIdCard());
                map.put("loanDate", user.getLoanDate());
                map.put("amount", user.getAmount());
                map.put("loanNo", user.getLoanNo());
                map.put("clearDate", user.getClearDate());
                map.put("signDate", user.getSignDate());
                java.util.Iterator<String> it = form.getFields().keySet().iterator();
                while (it.hasNext()) {
                    String name = it.next();
                    form.setField(name, map.get(name));
                }
                //true代表生成的PDF文件不可编辑
                stamper.setFormFlattening(true);
                stamper.close();
                Document doc = new Document();
                PdfCopy copy = new PdfCopy(doc, out);
                doc.open();
                PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
                copy.addPage(importPage);
                i++;
                doc.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
        return i;
    }

    public static void main(String[] args) {
        System.out.println("hello world");
    }
}
